from PIL import Image
import numpy as np
import knn_work.knn


def cut(filename, row, col):
    img = Image.open(filename)
    print(filename)
    width, height = img.size
    w = width // col
    h = height // row
    n = 0
    threshold = 80

    data_vectors = []

    for r in range(row):
        for c in range(col):
            box = (c * w, r * h, (c + 1) * w, (r + 1) * h)
            timg = img.crop(box).convert('L')
            timg = timg.resize((32, 32))
            table = []
            for i in range(256):
                if i < threshold:
                    table.append(1)
                else:
                    table.append(0)

            photo = timg.point(table, '1')
            np.set_printoptions(threshold=np.inf)
            # table = np.reshape(np.array(list(photo.getdata())), (1, 1024))
            table = np.reshape(np.array(list(photo.getdata())), (32, 32))
            print(table)
            table = np.reshape(np.array(list(photo.getdata())), (1, 1024))
            data_vectors.append(table)
            n += 1
    return data_vectors


def knnrun(filename):
    work_vectors = cut(filename, 1, 6)
    ans = knn_work.knn.work(6, work_vectors)

    ret = ""
    for i in ans:
        ret += i

    print(ret)
    return ret


if __name__ == "__main__":
    cut("workDigits/1.png")